package com.uuah.server.config.spring;

import org.springframework.context.ApplicationContext;

import com.uuah.api.lifecycle.IStartable;
import com.uuah.server.api.IUuahContext;
import com.uuah.server.api.config.registry.IRegistry;
import com.uuah.server.api.lifecycle.ILifecycleManager;
import com.uuah.server.config.ConfigResource;
import com.uuah.server.config.builders.AbstractConfigurationBuilder;
import com.uuah.server.exception.config.ConfigurationException;

public class SpringXmlConfigurationBuilder extends AbstractConfigurationBuilder {
	public static final String UUAH_DEFAULTS_CONFIG = "applicationContext-server.xml";

	private boolean useDefaultConfigResource = false;

	private IRegistry registry;

	public SpringXmlConfigurationBuilder(String configResource)
			throws ConfigurationException {
		super(configResource);
	}

	public SpringXmlConfigurationBuilder(ConfigResource[] configResources) {
		super(configResources);
	}

	protected void doConfigure(IUuahContext uuahContext) throws Exception {
		ConfigResource[] allResources = null;
		if (useDefaultConfigResource) {
			allResources = new ConfigResource[configResources.length + 1];
			allResources[0] = new ConfigResource(UUAH_DEFAULTS_CONFIG);
			System.arraycopy(configResources, 0, allResources, 1,
					configResources.length);
		} else {
			allResources = configResources;
		}
		createSpringRegistry(uuahContext, createApplicationContext(uuahContext,
				allResources));
	}

	protected ApplicationContext createApplicationContext(
			IUuahContext uuahContext, ConfigResource[] configResources)
			throws Exception {
		return new UuahApplicationContext(uuahContext, configResources);
	}

	protected void createSpringRegistry(IUuahContext uuahContext,
			ApplicationContext applicationContext) throws Exception {
		registry = new SpringRegistry(applicationContext);
		uuahContext.addRegistry(1, registry);
		registry.initialise();
	}

	protected void applyLifecycle(ILifecycleManager lifecycleManager)
			throws Exception {
		if (lifecycleManager.isPhaseComplete(IStartable.PHASE_NAME)) {
			lifecycleManager.applyPhase(registry.lookupObjects(Object.class),
					IStartable.PHASE_NAME);
		}
	}

	public boolean isUseDefaultConfigResource() {
		return useDefaultConfigResource;
	}

	public void setUseDefaultConfigResource(boolean useDefaultConfigResource) {
		this.useDefaultConfigResource = useDefaultConfigResource;
	}
}
